<?php

namespace App\Http\Controllers\API\Books;

use DB;
use App\Http\Controllers\API\ApiController;
use Illuminate\Http\Request;
use App\Eloqumd\System\Plate;
use App\Eloqumd\System\PlateUser;
use App\Eloqumd\Book\Book;
use App\Eloqumd\Book\BookArticleCate;
use App\Eloqumd\Book\BookArticleLatest;
use App\Eloqumd\Book\BookArticlePublish;
use App\Eloqumd\Book\BookArticleVersion;
use App\Validate\Book\BookValidator;
use App\Http\Controllers\GBS\Emails\MailSendController;

class BookController extends ApiController
{
    // 获取书籍列表
    public function getBookList(Request $request)
    {
        $page = (int)$request->input('page/d', 1) - 1;
        $limit = $request->input('limit/d', $this->limit);
        $keyword = $request->input('keyword', '');

        $where = null;
        // 快捷搜索
        if ($keyword) {
            $where[] = ['bk_name', 'like', "%{$keyword}%", 'OR'];
        }

        $where[] = ['bk_isdel', '=', 1, 'AND'];
        // 加入平台限制
        if ($this->apiUser['user_type'] == 1) {
            $where[] = ['bk_plate', '=', $this->apiUser['plate_code']];
        // 获取用户书籍-通过授权或协作筛选，现阶段暂无
        } elseif ($this->apiUser['user_type'] == 2) {
            $where[] = ['bk_user_id', '=', $this->apiUser['id']];
        }

        $totalCount = Book::where($where)->count();
        $listData = Book::where($where)
            ->offset($page)
            ->limit($limit)
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $listData[$k]['user_real_name'] = PlateUser::where('id', $v['bk_user_id'])->value('user_real_name');
            $listData[$k]['plate_name'] = Plate::where('plate_code', $v['bk_plate'])->value('plate_name');
        }

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list', trans('alg.Browse-Book-List-Info'));
    }

    // 根据数据ID获取书籍信息
    public function getBookInfoById(Request $request)
    {
        $bookId = $request->input('id', 0);
        $bookInfo = Book::find($bookId);

        return $this->jsonReturns(
            10000,
            $this->success,
            $bookInfo,
            'get',
            trans('alg.Get-Browse-Book-Info', ['name' => $bookInfo['bk_name'], 'id' => $bookId])
        );
    }

    // 创建书籍
    public function bookCreated(Request $request)
    {
        // 数据校验
        $param = $request->all();
        if (true !== $validateRes = BookValidator::bookCreated($param)) {
            return $this->jsonReturns(99999, $validateRes, [], 'create/verror', trans('alg.Create-Book-And-Validate-Error'));
        }

        // 数据处理
        DB::beginTransaction();
        try {
            $model = new Book;
            $model->bk_name = $param['bk_name'];
            $model->bk_desc = $param['bk_desc'];
            $model->bk_img = $param['bk_img'] ?? '';
            $model->bk_created_at = date('Y-m-d H:i:s');
            $model->bk_plate = $this->apiUser['plate_code'];
            $model->bk_user_id = $this->apiUser['id'];
            $model->save();

            DB::commit();

            return $this->jsonReturns(
                10000,
                $this->success,
                ['id' => $model->id],
                'create',
                trans('alg.Create-Book-Info-Success', [
                    'name' => $param['bk_name'],
                ])
            );
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), [], 'create/error', trans('alg.Create-Book-System-Error'));
        }
    }

    // 修改书籍
    public function bookModified(Request $request)
    {
        // 数据校验
        $param = $request->all();
        if (true !== $validateRes = BookValidator::bookModified($param)) {
            return $this->jsonReturns(99999, $validateRes, [], 'modify/verror', trans('alg.Modify-Book-And-Validate-Error'));
        }

        // 数据处理
        DB::beginTransaction();
        try {
            $model = Book::find($param['id']);
            $model->bk_name = $param['bk_name'];
            $model->bk_desc = $param['bk_desc'];
            $model->bk_img = $param['bk_img'] ?? '';
            $model->save();

            DB::commit();

            return $this->jsonReturns(
                10000,
                $this->success,
                ['id' => $param['id']],
                'modify',
                trans('alg.Modify-Book-Success', ['name' => $param['bk_name']])
            );
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), [], 'modify/error', trans('alg.Modify-Book-System-Error'));
        }
    }

    // 书籍删除
    public function bookDeleted(Request $request)
    {
        $id = $request->input('id', 0);

        if (!$id) {
            return $this->jsonReturns(99999, trans('alg.Illegal-Parameter', ['p' => 'id']), [], 'delete/verror', trans('alg.Delete-Book-And-Validate-Error'));
        }

        // 数据处理
        DB::beginTransaction();
        try {
            $model = Book::find($id);
            $model->bk_isdel = 0;
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, [], 'delete', trans('alg.Delete-Book-Success', ['name' => $model->bk_name]));
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), [], 'delete/error', trans('alg.Delete-Book-System-Error'));
        }
    }

    // 书籍公开
    public function bookOpenPublish(Request $request)
    {
        $id = $request->input('id', 0);

        if (!$id) {
            return $this->jsonReturns(99999, trans('alg.Illegal-Parameter', ['p' => 'id']), [], 'publish/verror', trans('alg.Publish-Book-And-Validate-Error'));
        }

        // 数据处理
        DB::beginTransaction();
        try {
            $model = Book::find($id);
            $model->bk_open = 1;
            $model->save();

            DB::commit();

            // 公开书籍通知给平台管理员
            MailSendController::bookPublishedMail($model);

            return $this->jsonReturns(10000, $this->success, [], 'publish', trans('alg.Publish-Book-Success', ['name' => $model->bk_name]));
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), [], 'publish/error', trans('alg.Publish-Book-System-Error'));
        }
    }

    // 文章书籍同步
    public function bookSynchronization(Request $request)
    {
        $id = $request->input('id', 0);

        if (!$id) {
            return $this->jsonReturns(99999, trans('alg.Illegal-Parameter', ['p' => 'id']), [], 'sync/verror', trans('alg.Sync-Book-And-Validate-Error'));
        }

        $bookInfo = Book::find($id);

        DB::beginTransaction();
        try {
            // 获取目录
            $catesData = BookArticleCate::where('book_id', $id)
                ->where('isdel', 1)
                ->pluck('id')
                ->toArray();
            // 获取编辑文章
            $artDatas = BookArticleLatest::whereIn('cate_id', $catesData)
                ->where('isdel', 0)
                ->where('ispublish', 0)
                ->pluck('sysunique')
                ->toArray();
            // 获取被删除文章
            $artBeDelDatas = BookArticleLatest::whereIn('cate_id', $catesData)
                ->where('isdel', 1)
                ->pluck('sysunique')
                ->toArray();

            $len = count($artDatas);
            for ($i = 0; $i < $len; $i++) {
                $artlData = BookArticleLatest::where('sysunique', $artDatas[$i])->first();
                BookArticleLatest::where('sysunique', $artDatas[$i])->update(['ispublish' => 1]);

                $artpData = BookArticlePublish::where('sysunique', $artDatas[$i])->first();
                if ($artpData['ispublish'] == 1) {
                    $pulishArt = $artlData->toArray();
                    // 数据转换
                    $pulishArt['versions'] = 'v-' . date('Ymd') . '-' . date('His');
                    unset($pulishArt['id']);
                    $pulishArt['ispublish'] = 1;
                    $artV = new BookArticleVersion;
                    $artV->insert($pulishArt);
                }
                // 更新
                BookArticlePublish::where('sysunique', $artDatas[$i])->update([
                    'cate_id' => $artlData['cate_id'],
                    'title' => $artlData['title'],
                    'content' => $artlData['content'],
                    'content_html' => $artlData['content_html'],
                    'orders' => $artlData['orders'],
                    'author' => $artlData['author'],
                    'ispublish' => 1,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
            }

            // 同步删除
            if (count($artBeDelDatas)) {
                BookArticlePublish::whereIn('sysunique', $artBeDelDatas)->update(['isdel' => 1]);
            }

            DB::commit();

            return $this->jsonReturns(10000, $this->success, [], 'sync', trans('alg.Sync-Book-Success', ['name' => $bookInfo['bk_name']]));
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), [], 'sync/error', trans('alg.Sync-Book-System-Error'));
        }
    }

    // 获取平台接入书籍根据平台号
    public function getOpenPublishBooksByPlate(Request $request)
    {
        $plate = $this->apiUser['plate_code'];
        $books = Book::where('bk_plate', $plate)
            ->where('bk_open', 1)
            ->where('bk_isdel', 1)
            ->get()
            ->toArray();

        return $this->jsonReturns(10000, $this->success, $books, 'list', trans('alg.Browse-Access-And-Publish-Book-List-Info'));
    }
}
